package com.sinszm.common.util;

import org.springframework.util.StringUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 绑定启动网卡或IP的工具类
 *
 * @author chenjianbo
 */
public final class BindNetAddressUtil {

    private static final String CLOUD_BIND_IP_KEY = "--spring.cloud.inetutils.default-ip-address=";

    /**
     * 获取多网卡IP列表
     *
     * @param regex     规则，例如：192.168，192.168.8，127.0
     * @return          IP列表
     */
    public static List<String> fetchIP(String regex) {
        List<String> address = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inet = networkInterface.getInetAddresses();
                while (inet.hasMoreElements()) {
                    InetAddress inetAddress = inet.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        address.add(inetAddress.getHostAddress());
                    }
                }
            }
            if (!StringUtils.isEmpty(regex)) {
                return address.stream()
                        .filter(str -> str.contains(regex))
                        .collect(Collectors.toList());
            }
            return address;
        } catch (SocketException e) {
            e.printStackTrace(System.out);
        }
        return new ArrayList<>();
    }

    /**
     * 初始化SpringCloud初始化绑定的IP问题
     *
     * @param regex     规则IP
     * @param args      参数集合
     * @return          环境参数配置
     */
    public static String[] initSpringCloudIpEnvironment(String regex, String[] args) {
        //处理IP
        List<String> addresses = fetchIP(regex);
        if (addresses == null || addresses.size() < 1) {
            throw new RuntimeException("获取IP失败，启动关闭。");
        }
        String ip = addresses.listIterator().next();
        //处理环境参数
        if (args == null) {
            throw new RuntimeException("启动参数异常，启动关闭。");
        }
        boolean k = false;
        for (String arg : args) {
            if (arg.contains(CLOUD_BIND_IP_KEY)) {
                k = true;
                break;
            }
        }
        if (k) {
            return args;
        }
        String[] resultArgs = new String[args.length + 1];
        System.arraycopy(args, 0, resultArgs, 0, args.length);
        resultArgs[resultArgs.length - 1] = CLOUD_BIND_IP_KEY + ip;
        return resultArgs;
    }

}
